import React, { useEffect, useState } from "react";
import { Tag } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { RootState } from "@/store";
import authRouteList from "@/utils/authRouteList";
import { setPath } from "@/store/modules/breadcrumbSlice";
import { setSelectedKey, addOpenKey } from "@/store/modules/menuSlice"; // 导入新的 action

// 递归查找路径对应的所有路由
const findRoute = (path: string, routes: any[]): any[] => {
  for (let route of routes) {
    if (route.path === path) {
      return [route];
    }
    if (route.children) {
      const res = findRoute(path, route.children);
      if (res.length > 0) {
        return [route, ...res];
      }
    }
  }
  return [];
};

const LayoutTags: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const navigate = useNavigate();
  const path = useSelector((state: RootState) => state.breadcrumb.path);
  const [tagItems, setTagItems] = useState<any[]>([{ title: "首页", href: "/home/index", active: true }]);

  useEffect(() => {
    dispatch(setPath(location.pathname));
  }, [location.pathname, dispatch]);

  useEffect(() => {
    const tagRoutes = findRoute(path, authRouteList);

    let filteredTagRoutes;
    if (tagRoutes.length > 1) {
      filteredTagRoutes = [tagRoutes[tagRoutes.length - 1]];
    } else {
      filteredTagRoutes = tagRoutes;
    }

    const newTag = filteredTagRoutes.map((route) => ({
      title: route.meta?.title,
      href: route.path,
      active: true,
    }));

    if (newTag.length > 0) {
      setTagItems((prevTags) => {
        const existingTag = prevTags.find((tag) => tag.href === newTag[0].href);
        if (existingTag) {
          return prevTags.map((tag) => ({
            ...tag,
            active: tag.href === newTag[0].href,
          }));
        } else {
          return [...prevTags.map((tag) => ({ ...tag, active: false })), ...newTag];
        }
      });
    }
  }, [path]);

  const handleTagClick = (href: string) => {
    // 查找当前路径对应的所有路由
    const tagRoutes = findRoute(href, authRouteList);
    // 找到相关的一级菜单
    const parentRoute = tagRoutes.length > 1 ? tagRoutes[0] : null;
    if (parentRoute) {
      dispatch(addOpenKey(parentRoute.path)); // 展开一级菜单
    }

    setTagItems((prevTags) =>
      prevTags.map((tag) => ({
        ...tag,
        active: tag.href === href,
      }))
    );
    dispatch(setSelectedKey(href)); // 同步更新菜单的选中状态
    navigate(href);
    console.log("tagItems", href);
  };

  return (
    <div>
      {tagItems.map((item, index) => (
        <Tag key={index} color={item.active ? "blue" : "default"} onClick={() => handleTagClick(item.href)} closable>
          {item.title}
        </Tag>
      ))}
    </div>
  );
};

export default LayoutTags;
